﻿#region Usings

using System;
using System.Collections.Generic;
using System.Linq;
using Omu.Awesome.Core;

#endregion

namespace XPressify.Core
{
    public static class EnumerableExtensions
    {
        //public static IEnumerable<T> GetPage<T>(this IQueryable<T> queryable, int page, int pageSize,
        //                                        bool ascending = false) where T : class
        //{
        //    return ascending
        //               ? queryable.OrderBy(o => o.Created).Skip((page - 1)*pageSize).Take(pageSize)
        //               : queryable.OrderByDescending(o => o.Created).Skip((page - 1)*pageSize).Take(pageSize);
        //}

        public static IEnumerable<T> GetPage<T, TKey>(this IEnumerable<T> queryable, int page, int pageSize,
                                                      Func<T, TKey> func, bool ascending = false) where T : class
        {
            return ascending
                       ? queryable.OrderBy(func).Skip((page - 1)*pageSize).Take(pageSize)
                       : queryable.OrderByDescending(func).Skip((page - 1)*pageSize).Take(pageSize);
        }

        //public static IPageable<T> GetPageable<T>(this IQueryable<T> queryable, int page, int pageSize,
        //                                          bool ascending = false) where T : class
        //{
        //    return new Pageable<T>
        //               {
        //                   Page = GetPage(queryable, page, pageSize, ascending),
        //                   PageCount = GetPageCount(pageSize, queryable.Count()),
        //                   PageIndex = page
        //               };
        //}

        public static IPageable<T> GetPageable<T, TKey>(this IEnumerable<T> queryable, int page, int pageSize,
                                                        Func<T, TKey> func, bool ascending = false)
            where T : class
        {
            return new Pageable<T>
                       {
                           Page = GetPage(queryable, page, pageSize, func, ascending),
                           PageCount = GetPageCount(pageSize, queryable.Count()),
                           PageIndex = page
                       };
        }

        private static int GetPageCount(int pageSize, int count)
        {
            var pages = count/pageSize;
            if (count%pageSize > 0) pages++;
            return pages;
        }
    }
}